using System;
using System.Collections;
using System.ComponentModel;
using System.Configuration;
using System.Drawing;
using System.Globalization;
using System.IO;
using System.Web;
using System.Web.Configuration;
using System.Web.UI;
using System.Web.UI.Design;
using System.Web.UI.Design.WebControls;
using System.Web.UI.WebControls;
using System.Windows.Forms;
using System.Xml;
using PickGold.Charting.Utilities;

namespace PickGold.Charting.Design
{
	internal class ChartWebDesigner : DataBoundControlDesigner
	{
		private System.Drawing.Image _chartImage;
		private static bool _configurationChecked;
		private const string _errorDesignTimeHtml = "<table cellpadding=4 cellspacing=0 width=\"{2}\" height=\"{3}\" style=\"width:{2};height{3};font-family:Tahoma;font-size:8pt;color:buttontext;background-color:buttonface;border: solid 1px;border-top-color:buttonhighlight;border-left-color:buttonhighlight;border-bottom-color:buttonshadow;border-right-color:buttonshadow\"><tr><td align=\"center\"><span style=\"font-weight:bold\">{1}</span><br/>{0}</td></tr></table>";
		private Timer _invalidateTimer = new Timer();
		private string _oldDataSource;
		internal static ChartWebDesigner controlDesigner;

		private void AddChartHttpHandler()
		{
			if (!_configurationChecked)
			{
				IWebApplication service = this.GetService(typeof(IWebApplication)) as IWebApplication;
				if (service != null)
				{
					System.Configuration.Configuration configuration = service.OpenWebConfiguration(false);
					if (configuration != null)
					{
						bool flag = false;
						HttpHandlersSection section = configuration.GetSection("system.web/httpHandlers") as HttpHandlersSection;
						if (section != null)
						{
							bool flag2 = false;
							foreach (HttpHandlerAction action in section.Handlers)
							{
								if (action.Type == typeof(ChartHttpHandler).AssemblyQualifiedName)
								{
									flag2 = true;
									break;
								}
							}
							if (!flag2)
							{
								HttpHandlerAction httpHandlerAction = new HttpHandlerAction("ChartImg.axd", typeof(ChartHttpHandler).AssemblyQualifiedName, "GET,HEAD", false);
								section.Handlers.Add(httpHandlerAction);
								flag = true;
							}
							ConfigurationSection section2 = configuration.GetSection("system.webServer");
							if ((section2 != null) && (section2.SectionInformation != null))
							{
								string rawXml = section2.SectionInformation.GetRawXml();
								XmlDocument xmlDocument = new XmlDocument();
								XmlDocumentFragment fragment = xmlDocument.CreateDocumentFragment();
								fragment.InnerXml = rawXml;
								XmlNode node = fragment.SelectSingleNode("system.webServer/handlers");
								if ((node != null) && (node.SelectSingleNode("add[@type=\"" + typeof(ChartHttpHandler).AssemblyQualifiedName + "\"]") == null))
								{
									if (node.SelectSingleNode("remove[@name=\"ChartImageHandler\"]") == null)
									{
										XmlNode node2 = xmlDocument.CreateElement("remove");
										AppendAttributeNode(xmlDocument, node2, "name", "ChartImageHandler");
										XmlNode refChild = node.SelectSingleNode("add[1]");
										if (refChild != null)
										{
											node.InsertBefore(node2, refChild);
										}
										else
										{
											node.AppendChild(node2);
										}
									}
									XmlNode oldChild = node.SelectSingleNode("add[@name=\"ChartImageHandler\"]");
									if (oldChild != null)
									{
										node.RemoveChild(oldChild);
									}
									XmlNode xmlNode = xmlDocument.CreateElement("add");
									AppendAttributeNode(xmlDocument, xmlNode, "name", "ChartImageHandler");
									AppendAttributeNode(xmlDocument, xmlNode, "preCondition", "integratedMode");
									AppendAttributeNode(xmlDocument, xmlNode, "verb", "GET,HEAD");
									AppendAttributeNode(xmlDocument, xmlNode, "path", "ChartImg.axd");
									AppendAttributeNode(xmlDocument, xmlNode, "type", typeof(ChartHttpHandler).AssemblyQualifiedName);
									node.AppendChild(xmlNode);
									section2.SectionInformation.SetRawXml(fragment.InnerXml);
									flag = true;
								}
							}
						}
						PagesSection section3 = (PagesSection)configuration.GetSection("system.web/pages");
						if (section3 != null)
						{
							TagPrefixInfo tagPrefixInformation = new TagPrefixInfo("asp", typeof(Chart).Namespace, typeof(Chart).Assembly.FullName, null, null);
							bool flag3 = false;
							for (int i = 0; i < section3.Controls.Count; i++)
							{
								TagPrefixInfo info2 = section3.Controls[i];
								if (string.Compare(info2.Namespace, tagPrefixInformation.Namespace, StringComparison.OrdinalIgnoreCase) == 0)
								{
									if (string.Compare(info2.Assembly, tagPrefixInformation.Assembly, StringComparison.OrdinalIgnoreCase) != 0)
									{
										section3.Controls.Remove(info2);
									}
									else
									{
										flag3 = true;
									}
									break;
								}
							}
							if (!flag3)
							{
								section3.Controls.Add(tagPrefixInformation);
								flag = true;
							}
						}
						if (configuration.AppSettings.Settings["ChartImageHandler"] == null)
						{
							configuration.AppSettings.Settings.Add("ChartImageHandler", @"storage=file;timeout=20;dir=c:\TempImageFiles\;");
							flag = true;
						}
						if (flag)
						{
							configuration.Save(ConfigurationSaveMode.Modified);
						}
					}
				}
				_configurationChecked = true;
			}
		}

		private static void AppendAttributeNode(XmlDocument xmlDocument, XmlNode xmlNode, string name, string value)
		{
			XmlAttribute node = xmlDocument.CreateAttribute(name);
			node.Value = value;
			xmlNode.Attributes.Append(node);
		}

		protected override void Dispose(bool disposing)
		{
			if (disposing)
			{
				if (this._invalidateTimer != null)
				{
					this._invalidateTimer.Dispose();
					this._invalidateTimer = null;
				}
				if (this._chartImage != null)
				{
					this._chartImage.Dispose();
					this._chartImage = null;
				}
			}
			base.Dispose(disposing);
		}

		public object GetDataSource()
		{
			object dataSource = null;
			string expression = null;
			DataBinding binding = base.DataBindings["DataSource"];
			if (binding != null)
			{
				expression = binding.Expression;
			}
			if (expression != null)
			{
				ISite site = base.Component.Site;
				if (site != null)
				{
					IContainer service = (IContainer)site.GetService(typeof(IContainer));
					if (service != null)
					{
						dataSource = service.Components[expression];
						if (!ChartImage.IsValidDataSource(dataSource))
						{
							dataSource = null;
						}
					}
				}
			}
			return dataSource;
		}

		public override string GetDesignTimeHtml()
		{
			string designTimeHtmlInternal = this.GetDesignTimeHtmlInternal();
			if (!this._invalidateTimer.Enabled)
			{
				this._invalidateTimer.Start();
			}
			return designTimeHtmlInternal;
		}

		private string GetDesignTimeHtmlInternal()
		{
			Chart component = (Chart)base.Component;
			controlDesigner = this;
			IWebFormsDocumentService service = (IWebFormsDocumentService)this.GetService(typeof(IWebFormsDocumentService));
			if (service != null)
			{
				component.WebFormDocumentURL = service.DocumentUrl;
			}
			if (this._chartImage != null)
			{
				this._chartImage.Dispose();
				this._chartImage = null;
			}
			using (MemoryStream stream = new MemoryStream())
			{
				ChartImageType imageType = component.ImageType;
				if (component.ImageType == ChartImageType.Emf)
				{
					component.ImageType = ChartImageType.Bmp;
				}
				component.SaveImage(stream);
				this._chartImage = System.Drawing.Image.FromStream(stream);
				component.ImageType = imageType;
			}
			StringWriter writer = new StringWriter(CultureInfo.InvariantCulture);
			HtmlTextWriter writer2 = new HtmlTextWriter(writer);
			System.Web.UI.WebControls.Image image = new System.Web.UI.WebControls.Image();
			image.ImageUrl = "about:blank";
			image.Width = component.Width;
			image.Height = component.Height;
			foreach (string str in component.Style.Keys)
			{
				if (((string.Compare(str, "Position", StringComparison.OrdinalIgnoreCase) == 0) || (string.Compare(str, "Left", StringComparison.OrdinalIgnoreCase) == 0)) || (string.Compare(str, "Top", StringComparison.OrdinalIgnoreCase) == 0))
				{
					image.Style[str] = component.Style[str];
				}
			}
			image.Style[HtmlTextWriterStyle.BackgroundColor] = "white";
			image.RenderControl(writer2);
			image.Dispose();
			return HttpUtility.UrlDecode(writer.ToString());
		}

		protected override string GetErrorDesignTimeHtml(Exception e)
		{
			Chart component = (Chart)base.Component;
			return string.Format(CultureInfo.InvariantCulture, "<table cellpadding=4 cellspacing=0 width=\"{2}\" height=\"{3}\" style=\"width:{2};height{3};font-family:Tahoma;font-size:8pt;color:buttontext;background-color:buttonface;border: solid 1px;border-top-color:buttonhighlight;border-left-color:buttonhighlight;border-bottom-color:buttonshadow;border-right-color:buttonshadow\"><tr><td align=\"center\"><span style=\"font-weight:bold\">{1}</span><br/>{0}</td></tr></table>", new object[] { SR.ExceptionChartPreviewNotAvailable, component.ID, component.Width.ToString(), component.Height.ToString() });
		}

		public override string GetPersistenceContent()
		{
			Chart component = (Chart)base.Component;
			bool serializing = component.Serializing;
			SerializationStatus serializationStatus = component.SerializationStatus;
			component.Serializing = true;
			component.SerializationStatus = SerializationStatus.Saving;
			string persistenceContent = base.GetPersistenceContent();
			component.Serializing = serializing;
			component.SerializationStatus = serializationStatus;
			return persistenceContent;
		}

		[Obsolete]
		public override string GetPersistInnerHtml()
		{
			Chart component = (Chart)base.Component;
			bool serializing = component.Serializing;
			SerializationStatus serializationStatus = component.SerializationStatus;
			component.Serializing = true;
			component.SerializationStatus = SerializationStatus.Saving;
			string persistInnerHtml = base.GetPersistInnerHtml();
			component.Serializing = serializing;
			component.SerializationStatus = serializationStatus;
			return persistInnerHtml;
		}

		public override void Initialize(IComponent component)
		{
			base.Initialize(component);
			base.SetViewFlags(ViewFlags.CustomPaint, true);
			this.AddChartHttpHandler();
			this._invalidateTimer.Interval = 200;
			this._invalidateTimer.Tick += new EventHandler(this.InvalidateTimer_Tick);
		}

		private void InvalidateTimer_Tick(object sender, EventArgs e)
		{
			this._invalidateTimer.Stop();
			base.Invalidate();
		}

		protected override void OnDataSourceChanged(bool forceUpdateView)
		{
			if (!base.RootDesigner.IsLoading)
			{
				if (this._oldDataSource != null)
				{
					Chart component = base.Component as Chart;
					if ((component != null) && (string.Compare(component.DataSourceID, this._oldDataSource, StringComparison.OrdinalIgnoreCase) != 0))
					{
						foreach (Series series in component.Series)
						{
							series.XValueMember = string.Empty;
							series.YValueMembers = string.Empty;
						}
					}
					this.UpdateDesignTimeHtml();
				}
				this._oldDataSource = base.DataSourceID;
			}
			base.OnDataSourceChanged(forceUpdateView);
		}

		protected override void OnPaint(PaintEventArgs e)
		{
			this._invalidateTimer.Stop();
			if (this._chartImage != null)
			{
				e.Graphics.DrawImageUnscaled(this._chartImage, e.ClipRectangle.Location);
			}
		}

		protected override void PostFilterProperties(IDictionary properties)
		{
			base.PostFilterProperties(properties);
			if (properties.Contains("PaletteCustomColors"))
			{
				PropertyDescriptor basePropertyDescriptor = (PropertyDescriptor)properties["PaletteCustomColors"];
				ColorExtendedArrayPropertyDescriptor descriptor2 = new ColorExtendedArrayPropertyDescriptor(basePropertyDescriptor);
				properties["PaletteCustomColors"] = descriptor2;
			}
		}

		internal void SetDirtyFlag()
		{
			this.SetDirtyFlag(false);
		}

		internal void SetDirtyFlag(bool raiseComponentChanged)
		{
			if (base.Tag != null)
			{
				base.Tag.SetDirty(true);
			}
			if (raiseComponentChanged)
			{
				base.RaiseComponentChanged(null, null, null);
			}
			base.Invalidate();
		}
	}
}

